<!--上传文件-->
<template>
  <div>
    <el-upload
      ref="upload"
      class="base-upload"
      name="FilePath"
      :multiple="multiple"
      action
      :headers="headers"
      :show-file-list="true"
      :show-upload-list="false"
      :limit="limit"
      :on-exceed="handleExceed"
      :accept="accept"
      :disabled="uploadLoad || disabled"
      :file-list="fileList"
      :auto-upload="false"
      :on-remove="handleRemove"
      :on-change="upload"
      :on-preview="loadFile"
      :before-upload="beforeUpload"
    >
      <!-- :http-request="uploadSectionFile" -->
      <!--上传loading -->
      <el-button size="small" type="primary">点击上传</el-button>
      <!-- <el-input name="businessType" hidden value="1"></el-input> -->
      <div slot="tip" class="el-upload__tip">{{ tipText }}</div>
    </el-upload>
    <BaseLoading v-if="showLoading" :loading-text="'上传中...'" />
  </div>
</template>

<script>
import { uploadFileInfo } from "../../api/Base";
import { getToken } from "../../utils/auth";
import { formdataify } from "@/utils/index";
import { GetFileInfoUrl } from "@/api/Base";
import axios from "axios";
export default {
  name: "BaseUploadFile",
  props: {
    tipText: {
      type: String,
      default: "只能上传pdf,doc,docx,xls,xlsx,zip,apk类型;并且不超过50M",
    },
    value: {
      type: Array,
      default: () => [],
    },
    filename: {
      type: String,
      default: "",
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true,
    },
    // 文件类型
    accept: {
      type: String,
      default: ".pdf,.doc,.xls,.docx,.xlsx,.zip,.apk",
    },
    // 文件大小
    fileSize: {
      type: Number,
      default: 51200,
    },
    // 禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 业务类型,请在后端代码Panna.ModuleSystem.Api中的BusinessType中查找对应的业务枚举值
    businessType: {
      type: String,
      default: "0",
    },
    limit: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      uploadUrl: "",
      uploadLoad: false,
      fileList: [],
      headers: { Authorization: getToken() },
      showLoading: false,
    };
  },
  watch: {
    value(val) {
      Array.isArray(val) && (this.fileList = val);
    },
  },
  methods: {
    // 上传完成
    upload(file, fileList) {
      if (file.status !== "ready") return;
      if (!this.beforeUpload(file, fileList)) {
        this.fileList = [];
        for (var i = 0; i < fileList.length - 1; i++) {
          this.fileList.push(fileList[i]);
        }
        return;
      }
      this.showLoading = true;
      const obj = {
        businessType: this.businessType,
        file: file.raw,
      };
      const form = formdataify(obj);
      uploadFileInfo(form)
        .then((res) => {
          const data = res.data;
          this.fileList.push({
            name: data.fileName,
            // url: `${data.protocol}${data.fileDomain}/${data.fileBucket}/${data.filePath}`,
            url2: data.filePath,
            fileSize: data.fileSize,
          });
          this.showLoading = false;
          this.$emit("input", this.fileList);
        })
        .catch((error) => {
          console.log(error);
          this.showLoading = false;
        });
    },
    // 上传校验 or 大小
    beforeUpload(file) {
      const fileTypes = this.accept.split(",");
      var testmsg = file.name.substring(file.name.lastIndexOf("."));
      const checkFormat = fileTypes.includes(testmsg);
      if (!checkFormat) {
        this.uploadLoad = false;
        this.$message.error(`请选择${this.accept}格式`);
      }
      const checkSize = file.size / 1024 < this.fileSize;
      if (!checkSize) {
        this.uploadLoad = false;
        this.$message.error(`文件必须小于${this.fileSize}KB！`);
      }
      return checkFormat && checkSize;
    },
    uploadSectionFile(file, fileList) {
      // var file = params.file;
      // this.businessType = 0;
      // this.uploadFile(file);
    },
    uploadFile(file) {
      var obj = {
        businessType: this.businessType,
        filePath: file.raw,
      };
      var form = formdataify(obj);
      uploadFileInfo(form).then((res) => {
        this.$refs.upload.uploadFiles = [];
      });
    },
    // 下载文件
    loadFile(file) {
      var url = GetFileInfoUrl(file.url);
      axios({
        method: "get",
        responseType: "blob", // 因为是流文件，所以要指定blob类型
        url: url, // 自己的服务器，提供的一个word下载文件接口
        headers: { Authorization: getToken() },
      }).then(({ data }) => {
        // 后端返回的是流文件
        const blob = new Blob([data]); // 把得到的结果用流对象转一下
        var a = document.createElement("a"); // 创建一个<a></a>标签
        a.href = URL.createObjectURL(blob); // 将流文件写入a标签的href属性值
        a.download = file.name || "123.zip"; // 设置文件名
        a.style.display = "none"; // 障眼法藏起来a标签
        document.body.appendChild(a); // 将a标签追加到文档对象中
        a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
        a.remove(); // 一次性的，用完就删除a标签
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择${this.limit}个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleRemove(file, fileList) {
      // this.$emit("deleteFile", `${this.$base}${file.response.data}`);
      this.fileList = this.fileList.filter((x) => x.url !== file.url);
      this.$emit("input", this.fileList);
    },
  },
};
</script>

<style lang="scss" scoped>
.base-upload {
  height: 136px;
  position: relative;
  .upload-button {
    width: 116px;
    height: 88px;
    background: #f7f8f9;
    border-radius: 4px;
    border: 1px #dedede dashed;
    img {
      display: block;
      width: 32px;
      height: auto;
      margin: 22px auto 10px;
    }
    span {
      display: block;
      width: 100%;
      font-size: 12px;
      line-height: 12px;
      font-weight: 500;
      color: #bfbfbf;
      transform: scale(0.8);
    }
  }
  .upload-cover {
    display: block;
    width: 116px;
    height: 88px;
    border-radius: 4px;
    object-fit: contain;
    border: 1px solid #dcdfe6;
  }
  .tip-text {
    position: absolute;
    left: 0;
    bottom: -10px;
    display: block;
    width: 100%;
    word-break: break-word;
    text-align: left;
    font-size: 6px;
    color: #666666;
    line-height: 18px;
    transform: scale(0.9);
  }
  .upload-loading {
    position: absolute;
    left: 0;
    top: 0;
    width: 116px;
    height: 88px;
    background-color: rgba(255, 255, 255, 0.8);
    z-index: 10;
    padding: 1px;
    box-sizing: border-box;
  }
  .no-upload {
    cursor: no-drop;
  }
}
</style>
